package com.haikesi.api.timertask.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haikesi.api.base.Constants;
import com.haikesi.api.base.Type;
import com.haikesi.api.base.User;
import com.haikesi.api.mode.dao.PlatformModeDao;
import com.haikesi.api.mode.domain.po.PlatformModePO;
import com.haikesi.api.timertask.dao.TimerTaskDao;
import com.haikesi.api.timertask.dao.TimerTaskModeDao;
import com.haikesi.api.timertask.domain.po.TimerTaskModePO;
import com.haikesi.api.timertask.domain.po.TimerTaskPO;
import com.haikesi.api.timertask.domain.vo.*;
import com.haikesi.api.timertask.service.ITimerTaskService;
import com.haikesi.api.typetemplate.dao.TypeTemplateMapper;
import com.haikesi.api.typetemplate.domain.po.TypeTemplatePO;
import com.haikesi.exception.BusinessException;
import com.haikesi.util.ApcosApiUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.Map.Entry;

@Service
@Transactional
public class TimerTaskService implements ITimerTaskService {

    @Autowired
    private TimerTaskDao dao;
    @Autowired
    private PlatformModeDao platformModeDao;
    @Autowired
    private TimerTaskModeDao timerTaskModeDao;
    @Autowired
    private TypeTemplateMapper typeTemplateMapperDao;

    @Override
    public List<TimerTaskVO> getList(TimerTaskSearchVO vo) {
        //当前用户没有组织机构就不需要带组织机构赛选功能
        TypeTemplatePO po = new TypeTemplatePO();
        User user = po.getUser();
        if (user == null) {
            vo.setOrganizationId(null);
        } else {
            if (user.getOrganizationId() != null) {
                //获取到最高级的组织机构ID
                String organizationId = typeTemplateMapperDao.getOrganizationId(user.getOrganizationId());
                vo.setOrganizationId(organizationId);
            } else {
                vo.setOrganizationId(null);
            }
        }
        List<TimerTaskVO> list = dao.getList(vo);
        return list;
    }

    @Override
    public TimerTaskPO addTimerTask(TimerTaskAddVO timerTaskAddVO) {
        //创建timerConfInfo
        JSONObject timerConfInfo = new JSONObject();
        if ("1".equals(timerTaskAddVO.getEnableTimer())) {
            timerConfInfo.put("enable_timer", "yes"); //激活定时
        } else {
            timerConfInfo.put("enable_timer", "no"); //激活定时
        }
        timerConfInfo.put("timer_name", timerTaskAddVO.getTimerName());     //定时名字
        timerConfInfo.put("timer_time", timerTaskAddVO.getTimerTime());     //定时时间
        timerConfInfo.put("timer_cycle", timerTaskAddVO.getTimerCycle());   //定时周期
        timerConfInfo.put("timer_readme", timerTaskAddVO.getTimerReadme()); //定时说明

        //模式ID
        List<String> modelList = timerTaskAddVO.getModelList();

        //平台模式的list
        List<PlatformModePO> platformModePOS = new ArrayList<>();

        for (String modelId : modelList) {
            // 查询所有已有的模式
            Example example = new Example(PlatformModePO.class);
            example.and().andEqualTo("modeId", modelId).andEqualTo("delFlag", 0);
            // 根据本地模式ID获取平台模式List
            List<PlatformModePO> list = platformModeDao.selectByExample(example);
            platformModePOS.addAll(list);
        }

        //平台模式的账号集合
        List<String> accountList = new ArrayList<>();
        for (PlatformModePO platformModePO : platformModePOS) {
            //判断list里面是否有账号，没有就添加到list
            if (!accountList.contains(platformModePO.getAccount())) {
                accountList.add(platformModePO.getAccount());
            }
        }

        //存放平台账号和定时任务ID
        JSONArray jsonArray = new JSONArray();
        for (String account : accountList) {
            int b = 1;
            //创建timerModeList
            JSONArray timerModeList = new JSONArray();
            for (int j = 0; j < platformModePOS.size(); j++) {
                if (account.equals(platformModePOS.get(j).getAccount())) {
                    PlatformModePO platformModePO = platformModePOS.get(j);
                    JSONObject json = new JSONObject();
                    json.put("mode_id", platformModePO.getPlatformModeId());
                    timerModeList.add(json);
                }
            }

            //获取平台定时任务ID
            JSONObject resultContent = ApcosApiUtils.addTimerTask(account, timerConfInfo, timerModeList);
            if (resultContent.get("resultContent") != null) {
                String id = resultContent.get("resultContent").toString();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(account, id);
                jsonArray.add(jsonObject);
            } else {
                throw new BusinessException(Type.EXCEPTION_FAIL);
            }
        }

        TimerTaskPO po = new TimerTaskPO();
        User user = po.getUser();
        //设置模板组织机构
        if (user != null && !user.getOrganizationId().isEmpty()) {
            timerTaskAddVO.setOrganizationId(user.getOrganizationId());
        }
        String _platformTimerTasks = JSON.toJSONString(jsonArray);
        //设置平台id（逗号隔开）
        timerTaskAddVO.setPlatformTimerTask(_platformTimerTasks);
        BeanUtils.copyProperties(timerTaskAddVO, po);
        po.preInsert();
        po.setId(UUID.randomUUID().toString());
        if ("1".equals(timerTaskAddVO.getEnableTimer())) {
            po.setEnableTimer(true);
        } else {
            po.setEnableTimer(false);
        }
        int i = dao.insertSelective(po);
        if (i == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
        TimerTaskModePO timerTaskModePO = new TimerTaskModePO();
        timerTaskModePO.setTimerTaskId(po.getId());
        for (String modelId : modelList) {
            timerTaskModePO.setModeId(modelId);
            int insert = timerTaskModeDao.insert(timerTaskModePO);
        }
        return po;
    }

    @Override
    public void updateTimerTask(TimerTaskUpdateVO timerTaskUpdateVO) {

        // 创建timerConfInfo
        JSONObject timerConfInfo = new JSONObject();
        if ("1".equals(timerTaskUpdateVO.getEnableTimer())) {
            timerConfInfo.put("enable_timer", "yes"); //激活定时
        } else {
            timerConfInfo.put("enable_timer", "no"); //激活定时
        }
        timerConfInfo.put("timer_name", timerTaskUpdateVO.getTimerName());     //定时名字
        timerConfInfo.put("timer_time", timerTaskUpdateVO.getTimerTime());     //定时时间
        timerConfInfo.put("timer_cycle", timerTaskUpdateVO.getTimerCycle());   //定时周期
        timerConfInfo.put("timer_readme", timerTaskUpdateVO.getTimerReadme()); //定时说明

        // 本地模式ID的list
        List<String> newModelList = timerTaskUpdateVO.getNewModelList();


        // 平台模式的list
        List<PlatformModePO> platformModePOS = new ArrayList<>();
        for (String modelId : newModelList) {
            // 查询所有已有的模式
            Example example = new Example(PlatformModePO.class);
            example.and().andEqualTo("modeId", modelId).andEqualTo("delFlag", 0);
            // 根据本地模式ID获取平台模式List
            List<PlatformModePO> list = platformModeDao.selectByExample(example);
            platformModePOS.addAll(list);
        }

        Map<String, String> mod = new HashMap<>();

        // map存放平台的账号所对应的平台模式ID
        Map<String, List<Map<String, String>>> map = new HashMap<>();
        for (int i = 0; i < platformModePOS.size(); i++) {
            if (!map.containsKey(platformModePOS.get(i).getAccount())) {
                List<Map<String, String>> list = new ArrayList<>();
                mod.put("mode_id", platformModePOS.get(i).getPlatformModeId());
                list.add(mod);
                map.put(platformModePOS.get(i).getAccount(), list);
            }else{
                List<Map<String, String>> list = map.get(platformModePOS.get(i).getAccount());
                mod.put("mode_id", platformModePOS.get(i).getPlatformModeId());
                list.add(mod);
                map.put(platformModePOS.get(i).getAccount(), list);
            }
        }

        //平台模式的账号集合
        /*List<String> accountList = new ArrayList<>();
        for (PlatformModePO platformModePO : platformModePOS) {
            //判断list里面是否有账号，没有就添加到list
            if (!accountList.contains(platformModePO.getAccount())) {
                accountList.add(platformModePO.getAccount());
            }
        }*/

        // 获取平台账号和定时任务ID
        String platformTimerTask = timerTaskUpdateVO.getPlatformTimerTask();
        JSONArray jsonArray1 = JSON.parseArray(platformTimerTask);
        // 获取选择模式的账号信息
        List<String> accountList = dao.getAccount(newModelList);
        for (int i = 0; i < jsonArray1.size(); i++) {
            Map<String, String> map1 = (Map<String, String>) jsonArray1.get(i);
            for (Entry<String, String> obj : map1.entrySet()) {
                String account = obj.getKey();
                String platformId = obj.getValue();
                if (!accountList.contains(account)) {
                    //调用平台定时任务删除接口
                    String s = ApcosApiUtils.delTimerTask(account, platformId);
                    if (!"0000".equals(s)) {
                        throw new BusinessException(Type.EXCEPTION_FAIL);
                    }else{
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(account, platformId);
                        int i1 = jsonArray1.indexOf(jsonObject);
                        jsonArray1.remove(i1);
                    }
                }else{
                    //修改
                    List<Map<String, String>> list = map.get(account);
                    //调用平台定时任务修改接口
                    String s = ApcosApiUtils.editTimerTask(account, platformId, timerConfInfo, list);
                    if (!"0000".equals(s)) {
                        throw new BusinessException(Type.EXCEPTION_FAIL);
                    }
                }
            }
        }

        //构建原本数据库里面的JSON账号装到list
        List<String> zh = new ArrayList<>();
        for (int i = 0; i < jsonArray1.size(); i++) {
            Map<String, String> map1 = (Map<String, String>) jsonArray1.get(i);
            for (Entry<String, String> obj : map1.entrySet()) {
                String account = obj.getKey();
                String platformId = obj.getValue();
                zh.add(account);
            }
        }
        for (int i = 0; i < accountList.size(); i++) {
            if(!zh.contains(accountList.get(i))){
                String newZh = accountList.get(i);
                String modeId = "";
                List<Map<String, String>> maps = map.get(newZh);
                /*for (PlatformModePO platformModePO : platformModePOS) {
                    //判断list里面是否有账号，没有就添加到list
                    if (platformModePO.getAccount().equals(newZh)) {
                        modeId = platformModePO.getPlatformModeId();
                    }
                }
                JSONArray timerModeList = new JSONArray();
                JSONObject json = new JSONObject();
                json.put("mode_id", modeId);
                timerModeList.add(json);*/
                JSONObject resultContent = ApcosApiUtils.addTimerTask(newZh, timerConfInfo, maps);
                if (resultContent.get("resultContent") != null) {
                    String id = resultContent.get("resultContent").toString();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(newZh, id);
                    jsonArray1.add(jsonObject);
                } else {
                    throw new BusinessException(Type.EXCEPTION_FAIL);
                }
            }
        }

        TimerTaskPO po = new TimerTaskPO();
        po.setId(timerTaskUpdateVO.getId());
        po.setPlatformTimerTask(JSON.toJSONString(jsonArray1));
        int i1 = dao.updateByPrimaryKeySelective(po);

        /*if (jsonArray1.size() > accountList.size()) {   // 取消勾选了的模式
            for (int i = 0; i < jsonArray1.size(); i++) {
                Map<String, String> map = (Map<String, String>) jsonArray1.get(i);
                for (Entry<String, String> obj : map.entrySet()) {
                    String account = obj.getKey();
                    String platformId = obj.getValue();
                    if (!accountList.contains(account)) {
                        //调用平台定时任务删除接口
                        String s = ApcosApiUtils.delTimerTask(account, platformId);
                        if (!"0000".equals(s)) {
                            throw new BusinessException(Type.EXCEPTION_FAIL);
                        }
                    }
                }
            }
        }else if(jsonArray1.size() < accountList.size()){   //新增了的模式
            List<String> zh = new ArrayList<>();
            for (int i = 0; i < jsonArray1.size(); i++) {
                Map<String, String> map = (Map<String, String>) jsonArray1.get(i);
                for (Entry<String, String> obj : map.entrySet()) {
                    String account = obj.getKey();
                    String platformId = obj.getValue();
                    zh.add(account);
                }
            }
            for (int i = 0; i < accountList.size(); i++) {
                if(!zh.contains(accountList.get(i))){
                    String newZh = accountList.get(i);
                    String modeId = "";
                    for (PlatformModePO platformModePO : platformModePOS) {
                        //判断list里面是否有账号，没有就添加到list
                        if (platformModePO.getAccount().equals(newZh)) {
                            modeId = platformModePO.getPlatformModeId();
                        }
                    }
                    JSONArray timerModeList = new JSONArray();
                    JSONObject json = new JSONObject();
                    json.put("mode_id", modeId);
                    timerModeList.add(json);
                    JSONObject resultContent = ApcosApiUtils.addTimerTask(newZh, timerConfInfo, timerModeList);
                    if (resultContent.get("resultContent") != null) {
                        String id = resultContent.get("resultContent").toString();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(newZh, id);
                        jsonArray1.add(jsonObject);
                        TimerTaskPO po = new TimerTaskPO();
                        po.setId(timerTaskUpdateVO.getId());
                        po.setPlatformTimerTask(JSON.toJSONString(jsonArray1));
                        int i1 = dao.updateByPrimaryKeySelective(po);
                    } else {
                        throw new BusinessException(Type.EXCEPTION_FAIL);
                    }
                }
            }
        }*/

        /*for (int i = 0; i < jsonArray1.size(); i++) {
            Map<String, String> map = (Map<String, String>) jsonArray1.get(i);
            for (Entry<String, String> obj : map.entrySet()) {
                String account = obj.getKey();
                String platformId = obj.getValue();
                JSONArray timerModeList = new JSONArray();
                for (int j = 0; j < newModelList.size(); j++) {
                    JSONObject json = new JSONObject();
                    json.put("mode_id", newModelList.get(j));
                    timerModeList.add(json);
                }
                //调用平台定时任务修改接口
                String s = ApcosApiUtils.editTimerTask(account, platformId, timerConfInfo, timerModeList);
                if (!"0000".equals(s)) {
                    throw new BusinessException(Type.EXCEPTION_FAIL);
                }
            }
        }*/

//        TimerTaskPO po = new TimerTaskPO();
        Example example = new Example(TimerTaskModePO.class);
        example.and().andEqualTo("timerTaskId", timerTaskUpdateVO.getId());
        int i = timerTaskModeDao.deleteByExample(example);

        TimerTaskModePO timerTaskModePO = new TimerTaskModePO();
        timerTaskModePO.setTimerTaskId(timerTaskUpdateVO.getId());
        for (int j = 0; j < newModelList.size(); j++) {
            timerTaskModePO.setModeId(newModelList.get(j));
            int insert = timerTaskModeDao.insert(timerTaskModePO);
        }

        User user = po.getUser();
        BeanUtils.copyProperties(timerTaskUpdateVO, po);
        po.preUpdate();

        if ("1".equals(timerTaskUpdateVO.getEnableTimer())) {
            po.setEnableTimer(true);
        } else {
            po.setEnableTimer(false);
        }
        int i11 = dao.updateByPrimaryKeySelective(po);
        if (i11 == Constants.SQL_RETUN_SUCCESS) {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public void delete(String id) {
        //根据ID查询定时任务
        Example example = new Example(TimerTaskPO.class);
        example.and().andEqualTo("id", id).andEqualTo("delFlag", 0);
        // 根据本地模式ID获取平台模式List
        List<TimerTaskPO> list = dao.selectByExample(example);

        if (list.size() == 1) {
            TimerTaskPO timerTaskPO = list.get(0);
            String ids = timerTaskPO.getPlatformTimerTask();
            JSONArray jsonArray = JSON.parseArray(ids);
            for (int i = 0; i < jsonArray.size(); i++) {
                Map<String, String> map = (Map<String, String>) jsonArray.get(i);
                for (Entry<String, String> obj : map.entrySet()) {
                    String account = obj.getKey();
                    String platformId = obj.getValue();
                    String s = ApcosApiUtils.delTimerTask(account, platformId);
                    if (!"0000".equals(s)) {
                        throw new BusinessException(Type.EXCEPTION_FAIL);
                    }
                }
            }

            // 逻辑删除本地定时任务
            timerTaskPO.setDelFlag(true);
            int i = dao.updateByPrimaryKeySelective(timerTaskPO);

            //删除中间表
            Example example1 = new Example(TimerTaskModePO.class);
            example1.and().andEqualTo("timerTaskId", id);
            int i1 = timerTaskModeDao.deleteByExample(example1);
        } else {
            throw new BusinessException(Type.EXCEPTION_FAIL);
        }
    }

    @Override
    public List<TimerTaskVO> getModeList(TimerTaskModeSearchVO timerTaskSeacherVO) {
        List<TimerTaskVO> modeList = timerTaskModeDao.getModeList(timerTaskSeacherVO);
        return modeList;
    }
}
